package com.ljw;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ThreadAnimationExample extends JFrame{
	
	public ThreadAnimationExample(){
		initUI();
	}

	private void initUI() {
		add(new Board5());
		
		setResizable(false);
		pack();
		
		setTitle("hahaha");
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args){
		EventQueue.invokeLater(new Runnable(){
			@Override
			public void run() {
				JFrame je = new ThreadAnimationExample();
				je.setVisible(true);
			}
		});
	}
}

class Board5 extends JPanel implements Runnable{
	
	private final int B_WIDTH = 350;
    private final int B_HEIGHT = 350;
    private final int INITIAL_X = -40;
    private final int INITIAL_Y = -40;
    private final int DELAY = 25;

    private Image hahaha;
    private Thread animator;
    private int x, y;
    
	public Board5(){
		initBoard();
	}

	private void initBoard() {
		setBackground(Color.BLACK);
        setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
        setDoubleBuffered(true);

        loadImage();

        x = INITIAL_X;
        y = INITIAL_Y;
		
	}

	private void loadImage() {
		ImageIcon ii = new ImageIcon("./resource/img/hahaha.jpg");
		hahaha = ii.getImage();
	}
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		drawImage(g);
	}

	private void drawImage(Graphics g) {
		g.drawImage(hahaha, x, y, null);
		Toolkit.getDefaultToolkit().sync();
	}
	
	private void cycle(){
		x += 1;
        y += 1;

        if (y > B_HEIGHT) {

            y = INITIAL_Y;
            x = INITIAL_X;
        }
	}

	@Override
	public void run() {
		
		long beforeTime, timeDiff, sleep;
		
		beforeTime = System.currentTimeMillis();
		
		while(true){
			cycle();
			repaint();
			
			timeDiff = System.currentTimeMillis() - beforeTime;
			sleep = DELAY - timeDiff;
			
			if(sleep < 0){
				sleep = 0;
			}
			
			try{
				Thread.sleep(sleep);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			
			beforeTime = System.currentTimeMillis();
		}
	}	
	
	@Override
    public void addNotify() {
        super.addNotify();

        animator = new Thread(this);
        animator.start();
    }
}